package com.aiyige.page.publish.selectprice;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.aiyige.BuildConfig;
import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.page.publish.selectprice.model.PriceGroup;
import com.aiyige.page.publish.selectprice.model.PriceItem;
import com.aiyige.setup.model.Setup;
import com.aiyige.setup.util.SetupUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.UIHelper;
import com.aiyige.utils.dialog.LoadingDialog;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;

@Route(path = ARouterConfig.SelectPricePage)
public class SelectPricePage extends AppCompatActivity {
    public static final String EXTRA_KEY_SELECT_PRICE_DATA = "com.aiyige.extra.EXTRA_KEY_SELECT_PRICE_DATA";
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.priceGroupRv)
    RecyclerView priceGroupRv;
    @BindView(R.id.priceItemRv)
    RecyclerView priceItemRv;
    PriceItemAdapter priceItemAdapter;
    PriceGroupAdapter priceGroupAdapter;
    @Autowired
    PriceItem selectedPrice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_select_price);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        titleTv.setText(R.string.select_price);
        priceItemAdapter = new PriceItemAdapter();
        priceGroupAdapter = new PriceGroupAdapter();
        priceGroupRv.setLayoutManager(new LinearLayoutManager(this));
        priceItemRv.setLayoutManager(new LinearLayoutManager(this));
        priceGroupAdapter.bindToRecyclerView(priceGroupRv);
        priceItemAdapter.bindToRecyclerView(priceItemRv);
        priceGroupAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                clearPriceGroupSelect();
                PriceGroup priceGroup = priceGroupAdapter.getItem(position);
                priceGroup.setSelected(true);
                priceGroupAdapter.notifyDataSetChanged();
                priceItemAdapter.setNewData(priceGroup.getPriceItemList());
            }
        });

        priceItemAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                clearPriceItemSelect();
                PriceItem priceItem = priceItemAdapter.getItem(position);
                priceItem.setSelected(true);
                priceItemAdapter.notifyDataSetChanged();
                doSelect(position);
            }
        });
        requestData();
    }

    public void doSelect(int position) {
        PriceItem priceItem = priceItemAdapter.getItem(position);
        Intent data = new Intent();
        data.putExtra(EXTRA_KEY_SELECT_PRICE_DATA, priceItem);
        setResult(RESULT_OK, data);
        finish();
    }

    public void requestData() {
        new RequestDataTask().execute();
    }

    public void clearPriceGroupSelect() {
        for (PriceGroup priceGroup : priceGroupAdapter.getData()) {
            priceGroup.setSelected(false);
        }
    }

    public void clearPriceItemSelect() {
        for (PriceGroup priceGroup : priceGroupAdapter.getData()) {
            for (PriceItem priceItem : priceGroup.getPriceItemList()) {
                priceItem.setSelected(false);
            }
        }
    }


    @OnClick({R.id.titleBackBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titleBackBtn:
                finish();
                break;
        }
    }

    public class RequestDataTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        List<PriceGroup> priceGroupList = new LinkedList<>();

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(SelectPricePage.this)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService().getSetup(SetupUtil.GROUP_TYPE_APPLE_PAY, BuildConfig.appVersion, SetupUtil.CHANNEL_ALL).execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                List<Setup> setupList = JSON.parseArray(json, Setup.class);
                List<PriceItem> priceItemList = new LinkedList<>();
                for (Setup setup : setupList) {
                    priceItemList.add(PriceItem.newBuilder()
                            .priceStr(StringUtils.platformDividendFormat(Double.parseDouble(String.valueOf(setup.getData().get("price")))))
                            .priceValue(Double.parseDouble(String.valueOf(setup.getData().get("price"))))
                            .priceId(String.valueOf(setup.getData().get("applePriceId")))
                            .build());
                }
                populatePriceGroupList(priceItemList);
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                restoreSelect();
            }
        }

        public void populatePriceGroupList(List<PriceItem> data) {
            priceGroupList.add(PriceGroup.newBuilder()
                    .lower(0)
                    .upper(Double.MAX_VALUE)
                    .title(StringUtils.getString(R.string.currency_symbols) + " 0-最大")
                    .build());
            outerLoop:
            for (PriceItem priceItem : data) {
                for (PriceGroup priceGroup : priceGroupList) {
                    if (priceGroup.inRange(priceItem.getPriceValue())) {
                        priceGroup.getPriceItemList().add(priceItem);
                        continue outerLoop;
                    }
                }
            }
            for (PriceGroup priceGroup : priceGroupList) {
                priceGroup.sort();
            }
        }

        public void restoreSelect() {
            Integer selectedPriceGroupIndex = null;
            Integer selectedPriceItemIndex = null;
            if (selectedPrice != null) {
                int priceGroupListSize = priceGroupList.size();
                outerLoop:
                for (int i = 0; i < priceGroupListSize; ++i) {
                    List<PriceItem> priceItemList = priceGroupList.get(i).getPriceItemList();
                    int priceItemListSize = priceItemList.size();
                    for (int j = 0; j < priceItemListSize; ++j) {
                        if (priceItemList.get(j).equals(selectedPrice)) {
                            selectedPriceGroupIndex = i;
                            selectedPriceItemIndex = j;
                            break outerLoop;
                        }
                    }
                }
            }

            if (selectedPriceGroupIndex != null && selectedPriceItemIndex != null) {
                priceGroupList.get(selectedPriceGroupIndex).setSelected(true);
                priceGroupList.get(selectedPriceGroupIndex).getPriceItemList().get(selectedPriceItemIndex).setSelected(true);
                priceGroupAdapter.setNewData(priceGroupList);
                priceItemAdapter.setNewData(priceGroupList.get(selectedPriceGroupIndex).getPriceItemList());
                ((LinearLayoutManager) priceGroupRv.getLayoutManager()).scrollToPositionWithOffset(selectedPriceGroupIndex, UIHelper.dip2px(0));
                ((LinearLayoutManager) priceItemRv.getLayoutManager()).scrollToPositionWithOffset(selectedPriceItemIndex, UIHelper.dip2px(0));
            } else {
                priceGroupList.get(0).setSelected(true);
                priceGroupAdapter.setNewData(priceGroupList);
                priceItemAdapter.setNewData(priceGroupList.get(0).getPriceItemList());
            }
        }


    }


}
